const express = require('express');
const router = express.Router();
const { Article } = require('../models')
const { success, failure } = require('../utils/responses');
const { NotFoundError } = require("../utils/errors");
//查询文章
router.get("/", async function (req, res) {
    try {
        const query = req.query
        const page = query.page || 1;
        const size = query.size || 10;
        const offset = (page - 1) * size;
        const condition = {
            limit: size,
            offset: offset,
            order: [['id', 'DESC']],
            attributes: { exclude: ['content'] },
        }
        const { count, rows } = await Article.findAndCountAll(condition)
        success(res, '查询文章成功。', { articles: rows, pagination: { total: count, page, size } });
    } catch (error) {
        failure(res, error);

    }
})
//查看文章详情
router.get("/:id", async function (req, res) {
    try {
        const id = req.params.id
        const article = await Article.findByPk(id)
        if (!article) {
            throw new NotFoundError(`ID: ${ id }的文章未找到。`)
        }
        success(res, '查询文章成功。', { article });
    } catch (error) {
        failure(res, error);
    }
})
module.exports = router;